-- 任务断层引导
local ExcelTaskConf = require("excel.Task")
local Msg = require("core.Msg")
local CopyCommon = require("copy.CopyCommon")
local BountyLogic = require("task.BountyLogic")
local TaskHelp = require("task.TaskHelp")
local RoleUIControl = require("role.RoleUIControl")

local DescCache = {}				-- 任务断层描述缓存 因为任务断层描述里面有些特殊字符是要替换的 为了避免频繁每次都字符串查找替换浪费cpu
DescFlyCache = DescFlyCache or {}	-- 任务断层描述中目标坐标的缓存 

local function cmp(a, b)
	return a.pri > b.pri
end

local function replaceDuancengDesc(desc, id)
	if desc == nil or #desc == 0 then return "" end
	if DescCache[id] then return DescCache[id] end
	
	DescFlyCache[id] = {}
	local strTemp = desc
	strTemp = TaskHelp.handleOpen(strTemp)
	strTemp = TaskHelp.handleCopy(strTemp, DescFlyCache[id])
	strTemp = TaskHelp.handleTarget(strTemp, DescFlyCache[id])
	strTemp = TaskHelp.handleMonster(strTemp, DescFlyCache[id])
	
	DescCache[id] = strTemp
	
	return strTemp
end

function sendDuancengInfo(human)
	if RoleUIControl.getMaxDoingMainTaskID(human) ~= 0 then return end

	local taskID = RoleUIControl.getMaxFinishMainTaskID(human) 
	local taskConfig = ExcelTaskConf.Task[taskID]
	if taskConfig == nil or taskConfig.nextTaskId == 0 then return end
	local taskNextConfig = ExcelTaskConf.Task[taskConfig.nextTaskId]
	
	if taskNextConfig.level <= human.db.lv then return end

	local tempTable = {}
	local tempTableCnt = 0
	for id, dConfig in pairs(ExcelTaskConf.Duanceng) do
		if human.db.lv >= dConfig.levelDown and human.db.lv <= dConfig.levelUp then
			local curCnt, maxCnt = getCountByConfig(human, dConfig)
			if curCnt < maxCnt then
				tempTableCnt = tempTableCnt + 1
				local strTemp = replaceDuancengDesc(dConfig.desc, id)
				strTemp = TaskHelp.handleTargetCnt(strTemp, curCnt, maxCnt)
				tempTable[tempTableCnt] = {str = strTemp, pri = dConfig.priority}
			end
		end
	end
	
	local msgRet = Msg.gc.GC_TASK_MAIN_DUANCENG
	if tempTableCnt > 1 then
		table.sort(tempTable, cmp)
		msgRet.duanceng[0] = 1
		msgRet.duanceng[1] = tempTable[1].str
		--msgRet.duanceng[2] = tempTable[2].str
	else
		msgRet.duanceng[0] = tempTableCnt
		for i = 1, tempTableCnt do
			msgRet.duanceng[i] = tempTable[i].str
		end
	end
	Msg.send(msgRet, human.fd)
end

local DUANCENG_TYPE_HANG		= 1 --挂机
local DUANCENG_TYPE_BOUNTY		= 2 --悬赏


function getCountByConfig(human, dConfig)
	local curCnt = 0
	local maxCnt = 0
	if dConfig.type >= 100 then
		-- 副本
		curCnt = CopyCommon.getCopyEnterCount(human, dConfig.type)
		maxCnt = CopyCommon.getCopyMaxEnterCount(human, dConfig.type)	
	elseif DUANCENG_TYPE_BOUNTY == dConfig.type then
		curCnt = BountyLogic.getCnt(human)
		maxCnt = BountyLogic.getMaxCnt(human)
	elseif DUANCENG_TYPE_HANG == dConfig.type then
		curCnt = 0
		maxCnt = 1
	end
	
	--print("maxCnt:", maxCnt, " curCnt:", curCnt ," type:", dConfig.type)
	return curCnt, maxCnt
end

function onBountyCntChange(human)
	sendDuancengInfo(human)
end

function onCopyCntChange(human)
	sendDuancengInfo(human)
end